import { HTTP_CUSTOM_CODE } from '@/enum/http-custom-code';
import { HttpException } from '@nestjs/common';
import Axios from 'axios';
import nodeXlsx from 'node-xlsx';

export function getFileForWebUrl(path: string) {
  return new Promise((resolve, reject) => {
    Axios.get(path, {
      responseType: 'arraybuffer',
    })
      .then((res) => {
        resolve(res.data);
      })
      .catch((err) => {
        reject(err);
      });
  });
}

type words = {
  wordContent: string;
  wordPronunciation: string;
  wordTranslate: string;
};

export const getExcelData = async (path: string) => {
  const sheetList = nodeXlsx.parse(await getFileForWebUrl(path));
  const result: words[] = [];
  try {
    const data = sheetList[0].data as [string, string, string][];
    if (Array.isArray(data)) {
      data.map((item, index) => {
        if (index !== 0) {
          const _item: words = {
            wordContent: item[0],
            wordTranslate: item[1],
            wordPronunciation: item[2],
          };
          result.push(_item);
        }
      });
    }
  } catch (error) {
    throw new HttpException(
      '解析excel错误',
      HTTP_CUSTOM_CODE.PARSE_EXCEL_FAILURE,
    );
  }
  return result;
};
